package com.atues.thread.syn;

public class UnsageBank {

    public static void main(String[] args) {
        Account account = new Account("123456789", 1000);
        Drawing drawing1 = new Drawing(account, 800);
        Drawing drawing2 = new Drawing(account, 900);
        drawing1.start();
        drawing2.start();
    }

}
class Drawing extends Thread {
    private Account account;
    private double drawAmount;

    public Drawing(Account account, double drawAmount) {
        this.account = account;
        this.drawAmount = drawAmount;
    }

    @Override
    public synchronized void run() {//锁方法没用，这个就是就是相当于锁当前对象实例   synchronized (this)

//        synchronized (account) {//同步代码块，使得同一时刻只有一个线程可以访问该代码块
        //必须要锁变化的量，并不是锁银行，而是账户；
            if (account.getBalance() >= drawAmount) {
                System.out.println(Thread.currentThread().getName() + "取钱成功，取出：" + drawAmount);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                account.setBalance(account.getBalance() - drawAmount);

                System.out.println(Thread.currentThread().getName() + "取钱后余额：" + account.getBalance());

            } else {
                System.out.println(Thread.currentThread().getName() + "取钱失败，余额不足");
            }
//        }
    }
}

class Account {
    private String accountNumber;
    private double balance;

    public Account(String accountNumber, double balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}
